package cn.melonlib.specials.auth.comp.service;

import cn.melonlib.cores.commons.comp.service.impl.WorkerBasicService;
import cn.melonlib.cores.jpa.model.bean.impl.DefaultQuery;
import cn.melonlib.specials.auth.model.entity.Account;
import cn.melonlib.specials.auth.model.entity.Tenant;
import cn.melonlib.specials.auth.model.enums.AccountType;
import org.intellij.lang.annotations.Language;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.List;

@Service
public class TenantService extends WorkerBasicService<Tenant> {

    @Resource
    private AccountManagerService accountManagerService;

    @Transactional(value = Transactional.TxType.REQUIRED,rollbackOn = Exception.class)
    public Tenant createTenant(Tenant tenant,String password) throws Exception{
        @Language("HQL") String validTenant="from Tenant where code=?1";
        List<Tenant> tenants=dao.<List<Tenant>,DefaultQuery>search(new DefaultQuery(validTenant, List.of(tenant.getCode()))).getResult();
        if(tenants.size()>0){
            return null;
        }
        tenant= dao.save(tenant).getResult();
        Account account=new Account();
        account.setAccount(tenant.getCode());
        account.setTenantId(tenant.getId());
        account.setTenantCode(tenant.getCode());
//        account.setTenant(getJsonMapper().writeValueAsString(tenant));
        account.setAccountTypes(getJsonMapper().writeValueAsString(List.of(AccountType.TENANT.name())));
        account.setActivated(true);
        accountManagerService.createAccount(account,password);
        return tenant;
    }

    public Tenant getTenant(String code){
        @Language("HQL") String hql="from Tenant where code=?1";
        List<Tenant> tenants= this.dao.<List<Tenant>,DefaultQuery>search(new DefaultQuery(hql,List.of(code))).getResult();
       if(tenants.isEmpty()){
           return null;
       }
        return tenants.get(0);
    }
}
